import { Component, OnInit, ViewChild } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalService } from 'ng-zorro-antd/modal';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

import { CommonService } from '../../../../app/services-common/common.service';
import { FinanceRecoveryOrderService } from './finance-recovery-order.service';
import { orderStateArrs, machineInspectionArrs } from '../../love-recyc-manage/love-recyc-manage.pipe';

@Component({
  selector: 'app-finance-recovery-order',
  templateUrl: './finance-recovery-order.component.html',
  styleUrls: ['./finance-recovery-order.component.scss']
})
export class FinanceRecoveryOrderComponent implements OnInit {

  @ViewChild('followUpRef') followUpRef: any;

  // 订单状态
  statusOptions: any = [...orderStateArrs];
  // 退货信息
  returnInfoOptions = [
    { value: 0, label: '无' },
    { value: 1, label: '有' }
  ];
  // 验机状态
  machineStateOptions: any = [...machineInspectionArrs];
  // 收款账户类型
  accountStausOption = [
    { value: 111, label: '微信' },
    { value: 121, label: '支付宝' }
  ];

  searchOptions = [
    { type: 1, labelText: '订单编号', valueKey: 'okey', value: '' },
    {
      type: 2,
      labelText: '订单状态',
      valueKey: 'ostat',
      value: [],
      multiple: true,
      selectBindKey: { key: 'id', label: 'label' },
      selectOptions: [...orderStateArrs],
    },
    {
      type: 2,
      labelText: '退货信息', // 退货信息 0: 无、1: 有
      valueKey: 'backI5addrid',
      value: '',
      selectOptions: this.returnInfoOptions,
    },
    {
      type: 2,
      labelText: '验机状态',
      valueKey: 'checkStatus',
      value: [],
      multiple: true,
      selectBindKey: { key: 'id', label: 'label' },
      selectOptions: [...machineInspectionArrs],
    },
    { type: 1, labelText: '下单机型', valueKey: 'umname', value: '' },
    { type: 1, labelText: '机器编码', valueKey: 'phoneCode', value: '' },
    {
      type: 2,
      labelText: '收款账户类型',
      valueKey: 'payway',
      value: '',
      selectOptions: this.accountStausOption,
    },
    { type: 1, labelText: '收款信息', valueKey: 'pay', value: '', placeholder: '请输入收款姓名/账号' },
    { type: 3, labelText: '下单时间', valueKey: ['otime11BeginTime', 'otime11EndTime'], value: [], isTimeSelect: true },
    { type: 3, labelText: '揽件时间', valueKey: ['otime13BeginTime', 'otime13EndTime'], value: [], isTimeSelect: true },
    { type: 3, labelText: '到货签收时间', valueKey: ['otime14BeginTime', 'otime14EndTime'], value: [], isTimeSelect: true },
    { type: 3, labelText: '成交时间', valueKey: ['otime19BeginTime', 'otime19EndTime'], value: [], isTimeSelect: true },
    { type: 3, labelText: '更新时间', valueKey: ['updateTime', 'endUpdateTime'], value: [], isTimeSelect: true },
  ];
  searchParams: any = {};

  tableParams: any = {
    loading: false,
    tableData: [],
    page: 1,
    pageSize: 20,
    total: 0
  };
  exportLoading: boolean = false;

  // 跟进 Modal
  initParams: any = {
    type: 1, // type  1、订单 2、售后 3、客户 4、出库 5、直降 6、退税 7、机器 8、商品
    modelId: 3, // 类型 1、旧的表示二手回收 2、表示二手商城 3、表示二手回收
    relationInformation: ''
  };

  // 打款
  isPaymentVisible: boolean = false;
  paymentReasons: any = [
    { value: 1, label: '用户未添加收款信息' },
    { value: 2, label: '收款信息错误' }
  ];
  paymentForm!: FormGroup;

  constructor(
    private fb: FormBuilder,
    private message: NzMessageService,
    private modal: NzModalService,
    private commonService: CommonService,
    private services: FinanceRecoveryOrderService
  ) { }

  ngOnInit(): void {
    // 打款失败
    this.paymentForm = this.fb.group({
      type: ['', [Validators.required]],
      remarks: ['']
    });
  }

  async loadTable() {
    let datas = {
      ...this.searchParams,
      page: this.tableParams.page,
      pageSize: this.tableParams.pageSize
    }
    this.tableParams.loading = true;
    const { code, data, message }: any = await this.services.queryRecoveryOrderList(datas);
    this.tableParams.loading = false;

    if (code === 0) {
      const { list, total } = data || {};
      this.tableParams.tableData = list || [];
      this.tableParams.total = total || 0;
    } else {
      this.message.error(message);
    }
  }

  queryData(params: any) {
    this.searchParams = params;
    this.tableParams.page = 1;
    this.setOfCheckedId.clear();
    this.loadTable();
  }

  resetData(params: any) {
    this.searchParams = params;
    this.tableParams.page = 1;
    this.setOfCheckedId.clear();
    this.loadTable();
  }

  // PageIndex Change
  onPageIndexChange(index: number) {
    this.tableParams.page = index;
    this.loadTable();
  }

  // PageSize Change
  onPageSizeChange(sizeNum: number) {
    this.tableParams.page = 1;
    this.tableParams.pageSize = sizeNum;
    this.loadTable();
  }

  // 跟进
  followModal(item: any) {
    this.initParams.relationInformation = item.id;
    this.followUpRef.isModelVisible = true;
  }

  exportTable() {
    this.modal.confirm({
      nzTitle: '提示',
      nzContent: '即将导出符合本页面筛选条件的数据，为了导出速度请尽可能的控制时间范围。确认导出？',
      nzOkText: '确认',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: async () => {
        this.exportLoading = true;
        const res: any = await this.services.exportRecoveryOrderData(this.searchParams);
        this.exportLoading = false;
        
        if (res.type == 'application/octet-stream') {
          this.commonService.downLoadBlobFile(res, '财务爱思回收订单管理');
        } else {
          this.message.error('导出失败');
        }
      },
      nzCancelText: '取消'
    });
  }

  // 原因选择
  reasonChange(value: any) {
    let tmpObj = this.paymentReasons.find((item: any) => item.value == value);
    this.paymentForm.get('remarks')?.setValue(tmpObj.label);
  }

  // Show Modal 打款失败
  showPaymentModal() {
    if (!this.setOfCheckedId.size) {
      this.message.warning('请先选择所需操作项');
      return
    }
    this.paymentForm.reset();
    this.isPaymentVisible = true;
  }

  // 打款成功 | 失败
  subPayment(type: number) {
    if (!this.setOfCheckedId.size) {
      this.message.warning('请先选择所需操作项');
      return
    }
    let params = {
      ids: [...this.setOfCheckedId].join(','),
      ostat: type === 0 ? 18 : 19 // 18-打款失败  19-打款成功
    }

    switch (type) {
      case 0:
        let failParams = {
          ...params,
          ...this.paymentForm.value
        }

        if (this.paymentForm.valid) {
          this.paymentInterface(failParams, type);
        } else {
          Object.values(this.paymentForm.controls).forEach(control => {
            if (control.invalid) {
              control.markAsDirty();
              control.updateValueAndValidity({ onlySelf: true });
            }
          });
        }
        return;
      case 1:
        this.paymentInterface(params, type);
        return;
    }
  }

  // 打款失败 | 成功
  paymentInterface(params: any, type?: number) {
    this.modal.confirm({
      nzTitle: '提示',
      nzContent: `是否要将所勾选的订单标记为打款 <b style="color: red;">${ type === 0 ? '失败' : '成功' }</b> ?`,
      nzOkText: '确认',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: async () => {
        const res: any = await this.services.subPaymentData(params);
        this.isPaymentVisible = false;
        if (res.code === 0) {
          // this.loadTable();
          this.message.success(res.data);
        } else {
          this.message.error(res.message);
        }
      },
      nzCancelText: '取消'
    });
  }

  /**
   * ----------------------------------------------------------------
   * Table Select
   * ----------------------------------------------------------------
   */
  checked = false;
  indeterminate = false;
  listOfCurrentPageData: readonly any[] = [];
  setOfCheckedId = new Set<number>();

  updateCheckedSet(id: number, checked: boolean): void {
    if (checked) {
      this.setOfCheckedId.add(id);
    } else {
      this.setOfCheckedId.delete(id);
    }
  }

  onItemChecked(id: number, checked: boolean): void {
    this.updateCheckedSet(id, checked);
    this.refreshCheckedStatus();
  }

  onAllChecked(value: boolean): void {
    this.listOfCurrentPageData.forEach(item => this.updateCheckedSet(item.id, value));
    this.refreshCheckedStatus();
  }

  onCurrentPageDataChange($event: readonly any[]): void {
    this.listOfCurrentPageData = $event;
    this.refreshCheckedStatus();
  }

  refreshCheckedStatus(): void {
    this.checked = this.listOfCurrentPageData.every(item => this.setOfCheckedId.has(item.id));
    this.indeterminate = this.listOfCurrentPageData.some(item => this.setOfCheckedId.has(item.id)) && !this.checked;
  }

  // order status filter
  orderStatusFilter(value: any, type: string) {
    if (value) {
      let tempObj = orderStateArrs.find((item: any) => {
        return item.id == value;
      })

      switch (type) {
        case 'text':
          return tempObj ? tempObj.label : '-';
        case 'color':
          return tempObj ? tempObj.color : '#333333';
      }
    } else {
      return '-';
    }
  }

  machineStatusFilter(value: any) {
    if (value) {
      let valArr = String(value).split(',');
      let tmpMachs = machineInspectionArrs.map((tag: any) => tag.id);
      let tmpArr: any = [];
      valArr.forEach((val: any) => {
        if (tmpMachs.includes(Number(val))) {
          let obj = machineInspectionArrs.find((ele: any) => ele.id == val);
          tmpArr.push(obj.label);
        }
      })

      return tmpArr.length ? (tmpArr.length > 3 ? ((tmpArr.slice(0, 3).join('、')) + '...') : tmpArr.join(','))  : '-';
    } else {
      return '-';
    }
  }

  // 验机合计
  sumMachineTotal(arr: any[], key: string, aprc: any) {
    let sum = 0;
    sum = arr.reduce((total: number, item: any) => {
      return (total || 0) + (item[key] || 0) + (aprc || 0);
    }, 0);
    return sum;
  }
}
